<template>
  <div class="page-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <div class="header-content">
        <h1 class="page-title">
          <el-icon class="title-icon">
            <DataBoard/>
          </el-icon>
          数据概览
        </h1>
        <p class="page-subtitle">欢迎使用 Easy Mart 管理系统</p>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="loadStatistics">
          <el-icon>
            <Refresh/>
          </el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon user-icon">
              <el-icon size="40">
                <User/>
              </el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ statistics.userCount || 0 }}</div>
              <div class="stats-label">用户总数</div>
              <div class="stats-trend">
                <span class="trend-text">较昨日 +{{ statistics.userGrowth || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon product-icon">
              <el-icon size="40">
                <Goods/>
              </el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ statistics.productCount || 0 }}</div>
              <div class="stats-label">商品总数</div>
              <div class="stats-trend">
                <span class="trend-text">在售 {{ statistics.activeProductCount || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon order-icon">
              <el-icon size="40">
                <Document/>
              </el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ statistics.orderCount || 0 }}</div>
              <div class="stats-label">订单总数</div>
              <div class="stats-trend">
                <span class="trend-text">今日 {{ statistics.todayOrderCount || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card class="stats-card">
          <div class="stats-content">
            <div class="stats-icon revenue-icon">
              <el-icon size="40">
                <Money/>
              </el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">¥{{ formatMoney(statistics.totalRevenue) || 0 }}</div>
              <div class="stats-label">总销售额</div>
              <div class="stats-trend">
                <span class="trend-text">今日 ¥{{ formatMoney(statistics.todayRevenue) || 0 }}</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>


    <!-- 详细统计 -->
    <el-row :gutter="20" class="detail-stats">
      <el-col :span="6">
        <el-card>
          <template #header>
            <span>订单状态分布</span>
          </template>
          <div class="stat-item">
            <span class="stat-label">待支付</span>
            <span class="stat-value">{{ orderStats.pendingPayment || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">待发货</span>
            <span class="stat-value">{{ orderStats.pendingDelivery || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">待收货</span>
            <span class="stat-value">{{ orderStats.pendingReceive || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已完成</span>
            <span class="stat-value">{{ orderStats.completedOrders || 0 }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card>
          <template #header>
            <span>商品库存状态</span>
          </template>
          <div class="stat-item">
            <span class="stat-label">在售商品</span>
            <span class="stat-value">{{ productStats.activeProducts || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">下架商品</span>
            <span class="stat-value">{{ productStats.inactiveProducts || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">库存不足</span>
            <span class="stat-value warning">{{ productStats.lowStockProducts || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">零库存</span>
            <span class="stat-value danger">{{ productStats.outOfStockProducts || 0 }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card>
          <template #header>
            <span>用户活跃度</span>
          </template>
          <div class="stat-item">
            <span class="stat-label">活跃用户</span>
            <span class="stat-value">{{ userStats.activeUsers || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">今日活跃</span>
            <span class="stat-value">{{ userStats.todayActiveUsers || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">本周新增</span>
            <span class="stat-value">{{ userStats.weekNewUsers || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">本月新增</span>
            <span class="stat-value">{{ userStats.monthNewUsers || 0 }}</span>
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <el-card>
          <template #header>
            <span>评论统计</span>
          </template>
          <div class="stat-item">
            <span class="stat-label">评论总数</span>
            <span class="stat-value">{{ commentStats.totalComments || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">今日评论</span>
            <span class="stat-value">{{ commentStats.todayComments || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已回复</span>
            <span class="stat-value">{{ commentStats.repliedComments || 0 }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">已隐藏</span>
            <span class="stat-value warning">{{ commentStats.hiddenComments || 0 }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 最新数据 -->
    <el-row :gutter="20" class="recent-data">
      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新订单</span>
              <el-button type="text" @click="router.push('/orders')">查看更多</el-button>
            </div>
          </template>
          <el-table
              v-loading="loadingOrders"
              :data="recentOrders"
              :show-header="false"
              style="width: 100%"
          >
            <el-table-column>
              <template #default="{ row }">
                <div class="order-item">
                  <div class="order-info">
                    <div class="order-number">{{ row.orderNo }}</div>
                    <div class="order-meta">
                      <span>{{ row.username }}</span>
                      <span class="order-time">{{ formatDateTime(row.createTime) }}</span>
                    </div>
                  </div>
                  <div class="order-status">
                    <div class="order-amount">¥{{ row.totalAmount }}</div>
                    <el-tag :type="getOrderStatusType(row.status)" size="small">
                      {{ getOrderStatusText(row.status) }}
                    </el-tag>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!loadingOrders && recentOrders.length === 0" class="empty-data">
            <el-empty :image-size="80" description="暂无订单数据"/>
          </div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card>
          <template #header>
            <div class="card-header">
              <span>最新评论</span>
              <el-button type="text" @click="router.push('/comments')">查看更多</el-button>
            </div>
          </template>
          <el-table
              v-loading="loadingComments"
              :data="recentComments"
              :show-header="false"
              style="width: 100%"
          >
            <el-table-column>
              <template #default="{ row }">
                <div class="comment-item">
                  <div class="comment-info">
                    <div class="comment-product">{{ row.productName }}</div>
                    <div class="comment-content">{{ formatCommentContent(row.content) }}</div>
                    <div class="comment-meta">
                      <span>{{ row.username }}</span>
                      <el-rate
                          v-model="row.rating"
                          :colors="['#ff4d4f', '#ff7a45', '#ffa940', '#52c41a', '#1890ff']"
                          disabled
                          size="small"
                      />
                      <span class="comment-time">{{ formatDateTime(row.createTime) }}</span>
                    </div>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <div v-if="!loadingComments && recentComments.length === 0" class="empty-data">
            <el-empty :image-size="80" description="暂无评论数据"/>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage} from 'element-plus'
import {DataBoard, Document, Goods, Money, Refresh, User} from '@element-plus/icons-vue'
import {formatDateTime} from '@/utils'
import {getCommentStatistics, getOrderStatistics, getProductStatistics, getUserStatistics} from '@/api/dashboard'
import {getOrderList} from '@/api/order'
import {getCommentList} from '@/api/comment'

// 路由
const router = useRouter()

// 响应式数据
const statistics = reactive({
  userCount: 0,
  userGrowth: 0,
  productCount: 0,
  activeProductCount: 0,
  orderCount: 0,
  todayOrderCount: 0,
  totalRevenue: 0,
  todayRevenue: 0
})

const recentOrders = ref([])
const recentComments = ref([])
const loadingOrders = ref(false)
const loadingComments = ref(false)

// 详细统计数据
const userStats = reactive({})
const productStats = reactive({})
const orderStats = reactive({})
const commentStats = reactive({})

// 方法

const formatMoney = (amount) => {
  if (!amount) return '0.00'
  return Number(amount).toFixed(2)
}

const formatCommentContent = (content) => {
  if (!content) return ''
  return content.length > 50 ? content.substring(0, 50) + '...' : content
}

const getOrderStatusText = (status) => {
  const statusMap = {
    0: '已取消',
    1: '待支付',
    2: '待发货',
    3: '待收货',
    4: '已完成',
    5: '已过期'
  }
  return statusMap[status] || '未知'
}

const getOrderStatusType = (status) => {
  const typeMap = {
    0: 'danger',
    1: 'warning',
    2: 'primary',
    3: 'info',
    4: 'success',
    5: 'danger'
  }
  return typeMap[status] || 'info'
}

const loadStatistics = async () => {
  try {
    // 并行调用各个独立的统计接口
    const [userResponse, productResponse, orderResponse, commentResponse] = await Promise.all([
      getUserStatistics(),
      getProductStatistics(),
      getOrderStatistics(),
      getCommentStatistics()
    ])

    // 处理用户统计数据
    if (userResponse.data) {
      const userStatistics = userResponse.data
      statistics.userCount = userStatistics.totalUsers || 0
      statistics.userGrowth = userStatistics.todayNewUsers || 0

      // 详细用户统计
      Object.assign(userStats, userStatistics)
    }

    // 处理商品统计数据
    if (productResponse.data) {
      const productStatistics = productResponse.data
      statistics.productCount = productStatistics.totalProducts || 0
      statistics.activeProductCount = productStatistics.activeProducts || 0

      // 详细商品统计
      Object.assign(productStats, productStatistics)
    }

    // 处理订单统计数据
    if (orderResponse.data) {
      const orderStatistics = orderResponse.data
      statistics.orderCount = orderStatistics.totalOrders || 0
      statistics.todayOrderCount = orderStatistics.todayOrders || 0
      statistics.totalRevenue = orderStatistics.totalAmount || 0
      statistics.todayRevenue = orderStatistics.todayAmount || 0

      // 详细订单统计
      Object.assign(orderStats, orderStatistics)
    }

    // 处理评论统计数据
    if (commentResponse.data) {
      const commentStatistics = commentResponse.data

      // 详细评论统计
      Object.assign(commentStats, commentStatistics)
    }

  } catch (error) {
    console.error('加载统计数据失败:', error)
    ElMessage.error('加载统计数据失败')
  }
}

const loadRecentOrders = async () => {
  try {
    loadingOrders.value = true
    // 获取最新订单数据
    const response = await getOrderList({
      current: 1,
      size: 5,
      sortBy: 'createTime',
      sortOrder: 'desc'
    })

    if (response.data && response.data.records) {
      recentOrders.value = response.data.records
    }
  } catch (error) {
    console.error('加载最新订单失败:', error)
    ElMessage.error('加载最新订单失败')
  } finally {
    loadingOrders.value = false
  }
}

const loadRecentComments = async () => {
  try {
    loadingComments.value = true
    // 获取最新评论数据
    const response = await getCommentList({
      current: 1,
      size: 5,
      sortBy: 'createTime',
      sortOrder: 'desc'
    })

    if (response.data && response.data.records) {
      recentComments.value = response.data.records
    }
  } catch (error) {
    console.error('加载最新评论失败:', error)
    ElMessage.error('加载最新评论失败')
  } finally {
    loadingComments.value = false
  }
}

// 生命周期
onMounted(() => {
  loadStatistics()
  loadRecentOrders()
  loadRecentComments()
})
</script>

<style scoped>
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--admin-space-xl);
  padding: var(--admin-space-lg);
  background: var(--admin-bg-primary);
  border-radius: var(--admin-radius-lg);
  box-shadow: var(--admin-shadow-sm);
  border: 1px solid var(--admin-border-light);
}

.header-content {
  flex: 1;
}

.page-title {
  display: flex;
  align-items: center;
  gap: var(--admin-space-sm);
  font-size: var(--admin-font-xl);
  font-weight: var(--admin-font-semibold);
  color: var(--admin-text-primary);
  margin: 0 0 var(--admin-space-sm) 0;
}

.title-icon {
  color: var(--admin-primary);
  font-size: var(--admin-font-xl);
}

.page-subtitle {
  color: var(--admin-text-secondary);
  margin: 0;
  font-size: var(--admin-font-sm);
  font-weight: var(--admin-font-medium);
}

.header-actions {
  display: flex;
  gap: var(--admin-space-sm);
}

.stats-row {
  margin-bottom: var(--admin-space-xl);
}

.stats-card {
  height: 160px;
  border-radius: var(--admin-radius-lg);
  border: 1px solid var(--admin-border-light);
  box-shadow: var(--admin-shadow-sm);
  transition: all 0.3s ease;
  overflow: hidden;
}

.stats-card:hover {
  box-shadow: var(--admin-shadow-hover);
  transform: translateY(-4px);
  border-color: var(--admin-primary-light);
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
  padding: var(--admin-space-lg);
  position: relative;
}

.stats-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, var(--admin-primary), var(--admin-primary-light));
}

.stats-icon {
  width: 80px;
  height: 80px;
  border-radius: var(--admin-radius-xl);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: var(--admin-space-lg);
  flex-shrink: 0;
  position: relative;
  overflow: hidden;
}

.stats-icon::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: inherit;
  opacity: 0.1;
  border-radius: inherit;
}

.user-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.3);
}

.product-icon {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(240, 147, 251, 0.3);
}

.order-icon {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(79, 172, 254, 0.3);
}

.revenue-icon {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
  box-shadow: 0 8px 24px rgba(67, 233, 123, 0.3);
}

.stats-info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: var(--admin-space-xs);
}

.stats-number {
  font-size: var(--admin-font-xxl);
  font-weight: var(--admin-font-bold);
  color: var(--admin-text-primary);
  line-height: var(--admin-line-height-sm);
  background: linear-gradient(135deg, var(--admin-text-primary), var(--admin-text-secondary));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.stats-label {
  font-size: var(--admin-font-sm);
  font-weight: var(--admin-font-medium);
  color: var(--admin-text-secondary);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.stats-trend {
  font-size: var(--admin-font-xs);
  line-height: var(--admin-line-height-sm);
}

.trend-text {
  color: var(--admin-success);
  font-weight: var(--admin-font-medium);
  padding: var(--admin-space-xs) var(--admin-space-sm);
  background: var(--admin-success-bg);
  border-radius: var(--admin-radius-sm);
  white-space: nowrap;
  display: inline-flex;
  align-items: center;
  border: 1px solid var(--admin-success-light);
}


.recent-data {
  margin-bottom: var(--admin-space-xl);
}

.recent-data .el-card {
  border-radius: var(--admin-radius-lg);
  border: 1px solid var(--admin-border-light);
  box-shadow: var(--admin-shadow-sm);
  transition: all 0.3s ease;
}

.recent-data .el-card:hover {
  box-shadow: var(--admin-shadow-md);
}

.recent-data .el-card__header {
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
  padding: var(--admin-space-md) var(--admin-space-lg);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: var(--admin-font-semibold);
  color: var(--admin-text-primary);
}

.order-item, .comment-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--admin-space-md) 0;
  border-bottom: 1px solid var(--admin-border-light);
  transition: all 0.3s ease;
}

.order-item:hover, .comment-item:hover {
  background: var(--admin-bg-hover);
  margin: 0 calc(-1 * var(--admin-space-lg));
  padding-left: var(--admin-space-lg);
  padding-right: var(--admin-space-lg);
  border-radius: var(--admin-radius-sm);
}

.order-item:last-child, .comment-item:last-child {
  border-bottom: none;
}

.order-info, .comment-info {
  flex: 1;
  min-width: 0;
}

.order-number, .comment-product {
  font-weight: var(--admin-font-semibold);
  color: var(--admin-text-primary);
  margin-bottom: var(--admin-space-xs);
  font-size: var(--admin-font-sm);
}

.comment-content {
  color: var(--admin-text-secondary);
  font-size: var(--admin-font-sm);
  margin-bottom: var(--admin-space-xs);
  line-height: var(--admin-line-height-md);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.order-meta, .comment-meta {
  font-size: var(--admin-font-xs);
  color: var(--admin-text-tertiary);
  display: flex;
  align-items: center;
  gap: var(--admin-space-sm);
}

.order-time, .comment-time {
  margin-left: auto;
  font-weight: var(--admin-font-medium);
}

.order-status {
  text-align: right;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: var(--admin-space-xs);
}

.order-amount {
  font-weight: var(--admin-font-semibold);
  color: var(--admin-warning);
  font-size: var(--admin-font-sm);
}

.empty-data {
  padding: var(--admin-space-xxl) 0;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-row .el-col {
    margin-bottom: var(--admin-space-md);
  }

  .detail-stats .el-col {
    margin-bottom: var(--admin-space-md);
  }
}

@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: var(--admin-space-md);
    align-items: flex-start;
  }

  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .stats-content {
    padding: var(--admin-space-md);
  }

  .stats-icon {
    width: 60px;
    height: 60px;
    margin-right: var(--admin-space-md);
  }

  .stats-number {
    font-size: var(--admin-font-xl);
  }
}

/* 详细统计样式 */
.detail-stats {
  margin-bottom: var(--admin-space-xl);
}

.detail-stats .el-card {
  border-radius: var(--admin-radius-lg);
  border: 1px solid var(--admin-border-light);
  box-shadow: var(--admin-shadow-sm);
  transition: all 0.3s ease;
}

.detail-stats .el-card:hover {
  box-shadow: var(--admin-shadow-md);
  transform: translateY(-2px);
}

.detail-stats .el-card__header {
  background: var(--admin-bg-secondary);
  border-bottom: 1px solid var(--admin-border-light);
  padding: var(--admin-space-md) var(--admin-space-lg);
  font-weight: var(--admin-font-semibold);
  color: var(--admin-text-primary);
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--admin-space-md) 0;
  border-bottom: 1px solid var(--admin-border-light);
  transition: all 0.3s ease;
}

.stat-item:hover {
  background: var(--admin-bg-hover);
  margin: 0 calc(-1 * var(--admin-space-lg));
  padding-left: var(--admin-space-lg);
  padding-right: var(--admin-space-lg);
}

.stat-item:last-child {
  border-bottom: none;
}

.stat-label {
  font-size: var(--admin-font-sm);
  color: var(--admin-text-secondary);
  font-weight: var(--admin-font-medium);
}

.stat-value {
  font-size: var(--admin-font-md);
  font-weight: var(--admin-font-semibold);
  color: var(--admin-text-primary);
}

.stat-value.warning {
  color: var(--admin-warning);
}

.stat-value.danger {
  color: var(--admin-error);
}

.stat-value.success {
  color: var(--admin-success);
}
</style>
